package com.njh.tools.common.phone;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 手机操作类
 */
public class PhoneUtils {
	
	/**
	 * 获取手机唯一id
	 * @return
	 */
	public static String getPhoneID(Context context){
		String imei = getIMEI(context);
		if(null!=imei&&!TextUtils.isEmpty(imei)){
			imei = getICCID(context);
		}
		return imei;
	}
	/**
	 * 获取手机型号
	 */
	public static String getPhoneModel() {
		try {
			return URLEncoder.encode(Build.MODEL, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 系统应用版本号
	 * @return
	 */
	@SuppressLint("InlinedApi")
	public static int getVersionCode() {
		int version = 0;
		try {
			version = Build.VERSION.SDK_INT;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 解析出短信
	 * 
	 * @param intent
	 *            从onReceive方法的参数
	 * @return
	 */
	public static final SmsMessage[] getMessagesFromIntent(Intent intent) {

		Object[] messages = (Object[]) intent.getSerializableExtra("pdus");

		byte[][] pduObjs = new byte[messages.length][];

		for (int i = 0; i < messages.length; i++)

		{

			pduObjs[i] = (byte[]) messages[i];

		}

		byte[][] pdus = new byte[pduObjs.length][];

		int pduCount = pdus.length;

		SmsMessage[] msgs = new SmsMessage[pduCount];

		for (int i = 0; i < pduCount; i++)

		{

			pdus[i] = pduObjs[i];

			msgs[i] = SmsMessage.createFromPdu(pdus[i]);

		}

		return msgs;

	}

	/**
	 * 获取当前运行的Activity名
	 * 
	 * @param act
	 * @return
	 */
	public static String getCurActivity(Activity act) {
		ActivityManager manager = (ActivityManager) act
				.getSystemService(Activity.ACTIVITY_SERVICE);
		RunningTaskInfo info = manager.getRunningTasks(1).get(0);
		String shortClassName = info.topActivity.getShortClassName(); // 类名

		return shortClassName;
	}

	public static String getMetaData(Context context, String name) {
		try {
			ApplicationInfo info = context.getPackageManager().getApplicationInfo(getPackageName(context), PackageManager.GET_META_DATA);
			return info.metaData.getString(name);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		} catch(Exception e2){
			e2.printStackTrace();
			return "";
		}
	}
	
	public static int getMetaDataInt(Context context, String name) {
		try {
			ApplicationInfo info = context.getPackageManager().getApplicationInfo(getPackageName(context), PackageManager.GET_META_DATA);
			return info.metaData.getInt(name);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return -1;
		} catch(Exception e2){
			e2.printStackTrace();
			return -1;
		}
	}
	
	/**
	 * 判断是否是飞行模式
	 * 
	 * @param context
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static boolean getAirplaneMode(Context context) {
		int isAirplaneMode = Settings.System.getInt(
				context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
				0);
		return (isAirplaneMode == 1) ? true : false;
	}

	/**
	 * 得到包信息
	 */
	public static PackageInfo getPackageInfo(Context ctx, String packageName) {
		PackageManager manager = ctx.getPackageManager();
		List<PackageInfo> pkgList = manager.getInstalledPackages(0);

		for (int i = 0; i < pkgList.size(); i++) {
			PackageInfo pI = pkgList.get(i);

			if (pI.packageName.equalsIgnoreCase(packageName))
				return pI;
		}

		return null;
	}


	public static boolean sendMsgIn(Activity act, String content, String to) {
		// 先判断有没有手机卡
		TelephonyManager tm = (TelephonyManager) act
				.getSystemService(Context.TELEPHONY_SERVICE);
		int telstate = tm.getSimState();
		if (telstate == 1 || telstate == 0) {
			Toast.makeText(act, "您没有手机卡", Toast.LENGTH_SHORT).show();
			return false;
		} else {
			SmsManager smsManager = SmsManager.getDefault();
			PendingIntent sentIntent = PendingIntent.getBroadcast(act, 0,
					new Intent(), 0);
			// 如果字数超过70,需拆分成多条短信发送
			if (content.length() > 70) {
				List<String> msgs = smsManager.divideMessage(content);
				for (String msg : msgs) {
					smsManager.sendTextMessage(to, null, msg, sentIntent, null);
				}
			} else
				smsManager.sendTextMessage(to, null, content, sentIntent, null);
			return true;
		}

	}

	/**
	 * 外部发送短信
	 * 
	 * @param act
	 * @param content
	 * @param to
	 */
	public static void sendMsgOut(Activity act, String content, String to) {
		Uri uri = Uri.parse("smsto:" + to);
		Intent it = new Intent(Intent.ACTION_SENDTO, uri);
		it.putExtra("sms_body", content);
		act.startActivity(it);
	}

	/**
	 * 获取当前应用的版本号（versioncode）
	 * 
	 * @return
	 */
	public static int getAppVersionCode(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;

		} catch (NameNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;

	}

	/**
	 * 获取当前应用的版本名
	 * 
	 * @return
	 */
	public static String getAppVersionName(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionName;

		} catch (NameNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 获取当前应用程序的包名
	 * 
	 * @return
	 */
	public static String getPackageName(Context context) {
		String packagename ="";
		try {
			packagename = context.getPackageName();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return packagename;
	}
	
	public static String getTopActName(Context ctx) {
		ActivityManager am = (ActivityManager) ctx
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

		return cn.getClassName();
	}

	/**
	 * 启动应用
	 * 
	 * @param packageName
	 */
	public static void startApp(Activity act, String packageName,
								String entrance) {
		if (!checkPackage(act, packageName)){
			return;// 包名不存在不处理
		}
		Intent intent = new Intent();
		intent.setComponent(new ComponentName(packageName, entrance));
		act.startActivity(intent);

	}

	/**
	 * 
	 * 检测该包名所对应的应用是否存在
	 * 
	 * @param packageName
	 * @return
	 */

	public static boolean checkPackage(Activity act, String packageName) {

		if (packageName == null || "".equals(packageName))
			return false;

		try {
			act.getPackageManager().getApplicationInfo(packageName,
					PackageManager.GET_UNINSTALLED_PACKAGES);
			return true;
		}

		catch (NameNotFoundException e) {
			return false;
		}

	}

	/**
	 *
	 * 检测该所对应的应用是否存在
	 *
	 * @return
	 */

	public static boolean checkClass(Activity act, String className) {

		if (className == null || "".equals(className))
			return false;

		try {
			Class.forName(className);
			return true;
		}

		catch (ClassNotFoundException e) {
			return false;
		}

	}
	
	public static int displayWidth(Context context) {
		try {
			DisplayMetrics dm = context.getResources()
					.getDisplayMetrics();
			return dm.widthPixels;
			
		} catch (Exception e) {
			return 480;
		}
	}

	public static int displayHeight(Context context) {
		DisplayMetrics dm = context.getResources()
				.getDisplayMetrics();
		return dm.heightPixels;
	}

	/**
	 * 屏幕分辨率
	 * 
	 * @return
	 */
	public static String getScreenPix(Context context) {
		return displayWidth(context) + "*" + displayHeight(context);
	}
	
	/**
	 * 获取imei
	 * @return
	 */
	public static String getIMEI(Context context){
		try {
			TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
			if(telephonyManager == null){
				return "";
			}
			return telephonyManager.getDeviceId();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * sim卡imsi
	 * @return
	 */
	public static String getIMSI(Context context){
		try {
			TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
			if(telephonyManager == null){
				return "";
			}
			String imsi = telephonyManager.getSubscriberId();
			return imsi==null?"":imsi.trim();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * sim卡背后20位字符串
	 * @return
	 */
	public static String getICCID(Context context){
		try {
			TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
			if(telephonyManager == null){
				return "";
			}
			String iccid = telephonyManager.getSimSerialNumber();
			return iccid==null?"":iccid.trim();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 获取手机型号(M355)
	 * @return
	 */
	public static String getModelNumber(){
		try {
			return URLEncoder.encode(Build.MODEL,"utf-8").replace("+", "");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 获取Android 版本(4.2.1)
	 * @return
	 */
	public static String getAndroidVersion(){
		try {
			return URLEncoder.encode(Build.VERSION.RELEASE, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 获取手机品牌(Meizu)
	 * @param
	 * @return
	 */
	public static String getBrand(){
		try {
			return URLEncoder.encode(Build.BRAND, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 获取 版本号（一系列数据的组合）(Flyme OS 3.5.2 (A19220))
	 * @return
	 */
	public static String getBuildNumber(){
		try {
			return URLEncoder.encode(Build.DISPLAY,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 获取sdk版本
	 * @return
	 */
	
	@SuppressWarnings("deprecation")
	public static String getSDKVersion(){
		return Build.VERSION.SDK;
	}
	
	/**
	 * 获取短信中心号
	 * @param context
	 * @return
	 */
	public static String getSmsCenter(Context context){
	    String[] projection = {"service_center"};
	    ContentResolver contentResolver = context.getContentResolver();
        Uri uri = Uri.parse("content://sms/inbox");
        Cursor cursor = contentResolver.query(uri, projection,null, null, "date desc");
        String centersms = "";
        int num = 0;
        if (null!=cursor&&cursor.moveToFirst()) {
        	int service_center = cursor.getColumnIndex("service_center");
        	do {
        		centersms 			= cursor.getString(service_center);
        		if(centersms==null || "".equalsIgnoreCase(centersms)){
        			centersms = "";
        			num++;
        			continue;
        		}else{
        			if(centersms.contains("+86")){
        				centersms = centersms.substring(3);
        			}
        			break;
        		}
			} while (cursor.moveToNext() && num<50);
        }
        return centersms;
	}
	public static String getPhoneNum(Context context){
		try {
			TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
			if(telephonyManager == null){
				return "";
			}
			return telephonyManager.getLine1Number();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 清除画布
	 * 
	 * @param c
	 */
	public static void cleanCanvas(Canvas c) {
		if (c != null) {
			c.drawColor(Color.TRANSPARENT, Mode.CLEAR);
		}
	}
	
	public void clearCanvas(Canvas canvas) {
		if (canvas == null)
			return;

		Paint paint = new Paint();
		paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
		canvas.drawPaint(paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC));
	}

//	/**
//	 * 获取APP名称
//	 * @return
//	 */
//	public static String getAppname() {
//		try{
//			return ApplicationEx.mContext.getResources().getString(R.string.app_name);
//		}catch (Exception e) {
//			return "";
//		}
//	}

	/**
	 * 获取CPU名称
	 * @return
	 */
	public static String getCpuName() {
		try {
			FileReader fr = new FileReader("/proc/cpuinfo");
			BufferedReader br = new BufferedReader(fr);
			String text = br.readLine();
			String[] array = text.split(":\\s+", 2);
			for (int i = 0; i < array.length; i++) {
			}
			return array[1].replace("+", "");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}
		return "";
	}

	public static String getPhoneFactory() {
		try {
			return Build.MANUFACTURER;
		}catch (Exception e){
			return "";
		}
	}

//	public static String getCommonParams(String url, Map<String, String> params) {
//		if(params == null) {
//			params = new HashMap<String, String>();
//		}
//		Map<String, String> map = getCommonMapParams();
//		map.putAll(params);
//		StringBuilder sBuilder = new StringBuilder();
//		if(!url.contains("?")) {
//			sBuilder.append("?");
//		} else {
//			sBuilder.append("&");
//		}
//		Set<? extends Map.Entry<String, String>> set = map.entrySet();
//		int i = 0;
//		for (Map.Entry<String, String> m : set) {
//			if(i != 0) {
//				sBuilder.append("&");
//			}
//			sBuilder.append(m.getKey());
//			sBuilder.append("=");
//			try {
//				if(null==m.getValue()){
//					sBuilder.append(URLEncoder.encode("", Constant.ENCODING));
//				}else{
//					sBuilder.append(URLEncoder.encode(m.getValue(), Constant.ENCODING));
//				}
//
//			} catch (UnsupportedEncodingException e) {
//				sBuilder.append(m.getValue());
//			}
//			i++;
//		}
//		return url + sBuilder.toString() ;
//	}

//	public static Map<String, String> getCommonMapParams() {
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("m1",getIMEI(ApplicationEx.mContext));					// imei
//		map.put("m2",getIMSI(ApplicationEx.mContext));					// imsi
//		map.put("m3",UserLogonInfo.getUUID());							// UUID
//		map.put("m4",getAppname());										// APP名称
//		map.put("m5",getAppVersionCode(ApplicationEx.mContext) + ""); 	// APP versioncode
//		map.put("m6",getAppVersionName(ApplicationEx.mContext));		// APP versionname
//		map.put("m7", Constant.PLATFORM);                            	// 接入平台（1 android 2 ios 3 wp）
//		map.put("m8",getAndroidVersion()); 								// Android 版本(4.2.1)
//		map.put("m9",getCpuName());										// CPU名称
//		map.put("m10", NetWorkUtils.getSIMType(
//				ApplicationEx.mContext)+""); 							// SIM卡类型 (移动、联通、电信)
//		map.put("m11",ChannelData.getAppChannelId(ApplicationEx.mContext));									//渠道id
//		map.put("m12",getICCID(ApplicationEx.mContext));				// iccid 卡识别码 0 CMWAP(移动)     1 CMNET(移动)     2 UNIWAP(联通)     3 UNINET(联通)     4 CTWAP(电信)     5 CTNET(电信)     6 WIFI     7 3G_CMWAP     8 3G_CMNET     9 4G_CMWAP     10 4G_CMNET
//		map.put("m13",displayWidth(ApplicationEx.mContext) + "");		// 分辨率宽
//		map.put("m14",displayHeight(ApplicationEx.mContext) + "");		// 分辨率高
//		map.put("m15",getModelNumber()); 								// 手机型号 (M355)
//		map.put("m16",PhoneUtils.getMetaDataInt(
//				ApplicationEx.mContext, Constant.APPID) + "");			//appid
//		map.put("m17",getPhoneFactory()); 								// 手机厂商
//		map.put("m18",getPackageName(ApplicationEx.mContext)); 			// 包名
//		return map;
//	}
	
	/**
	 * 保持屏幕唤醒状态（即背景灯不熄灭）
	 * @param on 是否唤醒
	 */
	@SuppressLint("Wakelock")
	@SuppressWarnings({ "unused", "deprecation" })
	public static void keepScreenOn(Context context, boolean on) {
		 WakeLock wakeLock = null;
		 try {
			 if(on){
				 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
				 wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
						 PowerManager.ON_AFTER_RELEASE, "==KeepScreenOn==");
				 wakeLock.acquire();
			 }else{
				 if(wakeLock!=null){
					 wakeLock.release();
					 wakeLock = null;
				 }
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}
	 }


}
